
#include "timer_object.h"

using namespace WtfEngine;

/**
 * Timer constructor - the timer will call the functor when its time is elapsed. It
 * binds to the particular app state passed, so timing effects (e.g pause, slo-mo)
 * are taken into account.
 **/
Timer::Timer(WtfEngine::IAppState::tWeakRefa rState, IFunctor<>::tRefa rFunc, WtfEngine::tGameTime tmo, bool bOneShot)
: mrState(rState), mrFunc(rFunc), mTimer(tmo), mStartTime(tmo), mbOneShot(bOneShot)
{
	mrState->BindEvent(this, EventHandler(new ObjFunctor<Timer>(this, &Timer::OnFrameStart),
		EventHandler::PRIO_GAME_CRITICAL));
};

void Timer::OnFrameStart()
{
	mTimer -= mrState->GetDelta();
	if(mTimer <= 0) {
		// We may be deleted here, so save a local copy of the functor we need to call
		IFunctor<>::tRef rFunc = mrFunc;
		if(mbOneShot) Destroy();
		else mTimer += mStartTime;
		(*mrFunc)();
	};
};

void Timer::Destroy()
{
	mrState->RemoveHandler(new ObjFunctor<Timer>(this, &Timer::OnFrameStart));
};
